let Vue;
//优化封装 提取 key value
const forEachFn = (obj, cb) => {
    Object.keys(obj).forEach(key => {
        cb(key, obj[key])
    })
}
class Store {
    //用来干嘛的 => 初始化数据
    constructor(options = {}) {
        // options
        // this.state = options.state
        //vuex的核心=>实现数据相应式
        //this.s.state.xxxx
        this.s = new Vue({
            data() {
                return {
                    state: options.state
                };
            },
        })

        //{}
        let getters = options.getters
        this.getters = {}
        //通过循环，拿出键值绑定get劫持对象的所有属性
        forEachFn(getters, (getterName, fn) => {
            Object.defineProperty(this.getters, getterName, {
                get: () => {
                    //函数的执行结果
                    return fn(this.state)
                }
            })
        })
        // Object.keys(getters).forEach((getterName) => {
        //     Object.defineProperty(this.getters, getterName, {
        //         get: () => {
        //             return getters[getterName](this.state)
        //         }
        //     })
        // })
        let mutations = options.mutations
        this.mutations = {}
        //通过循环，拿出键值绑定get劫持对象的所有属性
        // Object.keys(mutations).forEach((mutationName) => {
        //     this.mutations[mutationName] = (payload) => {
        //         mutations[mutationName](this.state, payload)
        //     }
        // })
        forEachFn(mutations, (mutationName, fn) => {
            this.mutations[mutationName] = (payload) => {
                //内部的第一个参数是状态
                fn(this.state, payload)
            }
        })
        let actions = options.actions
        this.actions = {}
        forEachFn(actions, (actionName, fn) => {
            this.actions[actionName]= (payload) => {
                //store
                fn(this, payload)
            }
            
        })
    }
    commit = (mutationName, payload) => {
        this.mutations[mutationName](payload)
    }
    //分发
    dispatch=(actionName,payload)=> {
        this.actions[actionName](payload)
    }
    //简化取值操作=>类的访问器
    get state() {
        return this.s.state
    }
}
const install = (_Vue) => {
    //_Vue=>vue 的构造函数
    Vue = _Vue;
    console.log("install");
    Vue.mixin({
        beforeCreate() {
            //new Vue渲染app的时候走一次
            //console.log("beforeCreate");
            if (this.$options && this.$options.store) {
                //根实例先添加
                this.$store = this.$options.store
            } else {
                //子
                this.$store = this.$parent && this.$parent.$store
            }
            //为什么不挂在Vue.prototype.axios
            //1. new Vue()每一个都会带store
            //2.不会污染原型
            //3.单独创建的实例，没有父亲没有store
        },
    })
}
export default {
    install, //给用户提供一个注册的方法默认调用
    Store
}